package com.wh.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{ for(int i=0;i<110;i++) ticket.sale();},"A").start();
        new Thread(()->{ for(int i=0;i<110;i++) ticket.sale();},"B").start();
        new Thread(()->{ for(int i=0;i<110;i++) ticket.sale();},"C").start();
    }
}

//lock三部曲
//1:new -->new ReentrantLock
//2:加锁-->lock
//3；解锁-->unlock
class Ticket {
    private int number = 100;

    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();

        try {
            //业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第" + number-- + "张票");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
